package com.yunkecn.wechatfilehandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Handler {

    private static Logger logger = LoggerFactory.getLogger(Handler.class);

    private static Handler handler;

    ExecutorService service;

    List<Integer> eatting;

    static {
        handler = new Handler();
        handler.service = Executors.newCachedThreadPool();
        handler.eatting = new CopyOnWriteArrayList<>();
        handler.receive();
    }

    public static Handler getInstance() {
        return handler;
    }


    public void receive() {
        synchronized (this) {
            List<Integer> apples = Box.getInstance().getApples();
            for (Integer integer : apples) {
                if (handler.eatting.contains(integer)) {
                    continue;
                }
                this.eatting.add(integer);
                service.execute(new Worker(integer));
            }
        }

    }

    public void finish(Integer apple) {
        synchronized (this) {
            Box.getInstance().remove(apple);
            this.eatting.remove(apple);
        }
    }



    private class Worker implements Runnable {

        private Integer apple;

        public Worker(Integer apple) {
            this.apple = apple;
        }

        @Override
        public void run() {


            logger.error(" will sleep [" + apple +"]");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.error(" weak up [" + apple +"]");
            Handler.getInstance().finish(apple);
        }
    }

    public static void main(String[] args) {
        Handler.getInstance();
        for (int i = 0; i < 100; i++) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("add");
                    Box.getInstance().add();
                    Handler.getInstance().receive();
                    System.out.println("notify");
                }
            }).start();
        }
    }


}
